package view;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Author;

abstract class Servlet extends HttpServlet {

	private static final long serialVersionUID = 241943820602691782L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		printGetPage(req, resp, resp.getWriter());
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		printPostPage(req, resp, resp.getWriter());
	}

	void printGetPage(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
		out.println("<html>");
		out.println(HtmlFactory.createPageHead(req.getServletContext().getRealPath("/")));
		out.println("<body>");

		out.println(HtmlFactory.createPageHeader(parseAuthor(req)));
		// TODO possivelmente criar um div de tamanho fixo id="content"
		fillGetContent(req, resp, out);

		out.println(HtmlFactory.createPageFooter());

		out.println("</body>");
		out.println("</html>");
	}

	void printPostPage(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
		if (out != null) {
			out.println("<html>");
			out.println(HtmlFactory.createPageHead(req.getServletContext().getRealPath("/")));
			out.println("<body>");

			out.println(HtmlFactory.createPageHeader(parseAuthor(req)));
		}
		// TODO possivelmente criar um div de tamanho fixo id="content"
		fillPostContent(req, resp, out);
		if (out != null) {
			out.println(HtmlFactory.createPageFooter());

			out.println("</body>");
			out.println("</html>");
		}
	}

	private Author parseAuthor(HttpServletRequest req) {
		HttpSession session = req.getSession(false);
		if (session != null) {
			return (Author) session.getAttribute("author");
		}
		return null;
	}

	abstract void fillGetContent(HttpServletRequest request, HttpServletResponse response, PrintWriter out);

	abstract void fillPostContent(HttpServletRequest request, HttpServletResponse response, PrintWriter out);
}
